package info

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/yusufpapurcu/wmi"
	"gopkg.in/ini.v1"
)

type CIM_NetworkPort struct {
	Caption                                          string    `json:"描述"`
	Description                                      string    `json:"说明"`
	InstallDate                                      time.Time `json:"安装时间"`
	Name                                             string    `json:"名称"`
	Status                                           string    `json:"状态"`
	Availability                                     uint16    `json:"可用性"`
	ConfigManagerErrorCode                           uint32    `json:"错误代码"`
	ConfigManagerUserConfig                          bool      `json:"用户定义的配置"`
	CreationClassName                                string
	DeviceID                                         string   `json:"逻辑设备ID"`
	ErrorCleared                                     bool     `json:"错误是否清除"`
	ErrorDescription                                 string   `json:"错误描述"`
	LastErrorCode                                    uint32   `json:"最后错误"`
	PNPDeviceID                                      string   `json:"即插即用设备ID"`
	PowerManagementCapabilities                      []uint16 `json:"电源相关功能的数组"`
	PowerManagementSupported                         bool     `json:"电源管理支持"`
	StatusInfo                                       uint16   `json:"逻辑设备的状态"`
	SystemCreationClassName                          string
	SystemName                                       string
	Speed                                            uint64   `json:"端口的带宽"`
	MaxSpeed                                         uint64   `json:"端口的最大带宽"`
	RequestedSpeed                                   uint64   `json:"端口请求的带宽"`
	UsageRestriction                                 uint16   `json:"使用限制"`
	PortType                                         uint16   `json:"端口类型"`
	OtherPortType                                    string   `json:"模块类型"`
	OtherNetworkPortType                             string   `json:"其他网络端口类型"`
	PortNumber                                       uint16   `json:"端口编号"`
	LinkTechnology                                   uint16   `json:"链接类型的枚举"`
	OtherLinkTechnology                              string   `json:"其他连接技术"`
	PermanentAddress                                 string   `json:"硬编码地址"`
	NetworkAddresses                                 []string `json:"网络地址"`
	FullDuplex                                       bool     `json:"全双工模式下运行"`
	AutoSense                                        bool     `json:"是否能够自动确定所连接网络媒体"`
	SupportedMaximumTransmissionUnit                 uint64   `json:"可支持的最大传输单元 "`
	ActiveMaximumTransmissionUnit                    uint64   `json:"可以支持的活动或协商的最大传输单元"`
	InterfaceDescription                             string   `json:"接口描述"`
	InterfaceName                                    string   `json:"网络接口的本地唯一标识符"`
	NetLuid                                          uint64   `json:"网络接口的本地唯一标识符id"`
	InterfaceGuid                                    string   `json:"网络接口的GUID"`
	InterfaceIndex                                   uint32   `json:"网络接口的索引"`
	DeviceName                                       string   `json:"设备对象的名称"`
	NetLuidIndex                                     uint32   `json:"网络适配器的索引"`
	Virtual                                          bool     `json:"模拟物理网卡"`
	Hidden                                           bool     `json:"隐藏"`
	NotUserRemovable                                 bool     `json:"网络适配器删除"`
	IMFilter                                         bool     `json:"中间筛选器"`
	InterfaceType                                    uint32   `json:"接口类型"`
	HardwareInterface                                bool     `json:"硬件设备提供"`
	WdmInterface                                     bool     `json:"WDM总线驱动程序"`
	EndPointInterface                                bool     `json:"端点接口"`
	ISCSIInterface                                   bool     `json:"iSCSI使用"`
	NdisMedium                                       uint32   `json:"网络适配器介质类型"`
	NdisPhysicalMedium                               uint32   `json:"物理媒体类型"`
	InterfaceOperationalStatus                       uint32   `json:"运行状态"`
	OperationalStatusDownDefaultPortNotAuthenticated bool     `json:"默认端口未经过身份验证"`
	OperationalStatusDownMediaDisconnected           bool     `json:"已断开连接"`
	OperationalStatusDownInterfacePaused             bool     `json:"处于暂停状态"`
	OperationalStatusDownLowPowerState               bool     `json:"处于低功耗状态"`
	InterfaceAdminStatus                             uint32   `json:"网络适配器管理状态"`
	MediaConnectState                                uint32   `json:"网络适配器连接状态"`
	MtuSize                                          uint32   `json:"最大传输单元"`
	VlanID                                           uint16   `json:"网络适配器上设置的虚拟LAN标识符"`
	TransmitLinkSpeed                                uint64   `json:"传输链路速度"`
	ReceiveLinkSpeed                                 uint64   `json:"接收链路速度"`
	PromiscuousMode                                  bool     `json:"混杂模式"`
	DeviceWakeUpEnable                               bool     `json:"网络适配器支持LAN唤醒功能"`
	ConnectorPresent                                 bool     `json:"物理适配器"`
	MediaDuplexState                                 uint32   `json:"网络适配器的媒体双工状态"`
	DriverDate                                       string   `json:"网络适配器驱动程序日期1"`
	DriverDateData                                   uint64   `json:"网络适配器驱动程序日期"`
	DriverVersionString                              string   `json:"网络适配器驱动程序版本"`
	DriverName                                       string   `json:"网络适配器驱动程序的名称"`
	DriverDescription                                string   `json:"网络适配器驱动程序的说明"`
	MajorDriverVersion                               uint16   `json:"网络适配器驱动程序的主要版本"`
	MinorDriverVersion                               uint16   `json:"网络适配器驱动程序的次要版本"`
	DriverMajorNdisVersion                           uint8    `json:"网络适配器驱动程序遵循主要NDIS版本"`
	DriverMinorNdisVersion                           uint8    `json:"适配器驱动程序符合次要NDIS版本"`
	DriverProvider                                   string   `json:"驱动程序名称"`
	ComponentID                                      string   `json:"部件ID"`
	LowerLayerInterfaceIndices                       []uint32 `json:"低层接口索引"`
	HigherLayerInterfaceIndices                      []uint32 `json:"高层接口索引"`
	AdminLocked                                      bool     `json:"管理状态"`
}
type Win32_NetworkAdapter struct {
	AdapterType                 string `json:"网络介质"`
	AdapterTypeID               uint16 `json:"网络介质id"`
	AutoSense                   bool   `json:"自动确定附加网络速度"`
	Availability                uint16 `json:"可用性"`
	Caption                     string `json:"简述"`
	ConfigManagerErrorCode      uint32 `json:"错误代码"`
	ConfigManagerUserConfig     bool
	CreationClassName           string
	Description                 string    `json:"描述"`
	DeviceID                    string    `json:"网络适配器的唯一标识符"`
	ErrorCleared                bool      `json:"清除LastErrorCode中报告的错误"`
	ErrorDescription            string    `json:"错误的详细信息"`
	GUID                        string    `json:"全局唯一标识符"`
	Index                       uint32    `json:"索引号"`
	InstallDate                 time.Time `json:"安装时间"`
	Installed                   bool
	InterfaceIndex              uint32   `json:"接口的索引值"`
	LastErrorCode               uint32   `json:"最后一个错误代码"`
	MACAddress                  string   `json:"MAC地址"`
	Manufacturer                string   `json:"制造商的名称"`
	MaxNumberControlled         uint32   `json:"直接可寻址端口的最大数目"`
	MaxSpeed                    uint64   `json:"最大速度"`
	Name                        string   `json:"名称"`
	NetConnectionID             string   `json:"网络连接的名称"`
	NetConnectionStatus         uint16   `json:"连接到网络的状态"`
	NetEnabled                  bool     `json:"是否已启用"`
	NetworkAddresses            []string `json:"网络地址数组"`
	PermanentAddress            string   `json:"配器的网络地址"`
	PhysicalAdapter             bool     `json:"是否物理适配器"`
	PNPDeviceID                 string   `json:"插即用逻辑设备的设备标识符"`
	PowerManagementCapabilities []uint16 `json:"电源相关功能"`
	PowerManagementSupported    bool
	ProductName                 string `json:"产品名称"`
	ServiceName                 string `json:"服务名称"`
	Speed                       uint64 `json:"速度"`
	Status                      string `json:"状态"`
	StatusInfo                  uint16 `json:"逻辑设备的状态"`
	SystemCreationClassName     string
	SystemName                  string
	TimeOfLastReset             time.Time `json:"上次重置网络适配器的日期和时间"`
}

// 网卡配置信息
type Win32_NetworkAdapterConfiguration struct {
	Caption                      string `json:"说明"`
	Description                  string `json:""`
	ArpAlwaysSourceRoute         bool
	ArpUseEtherSNAP              bool
	DatabasePath                 string    `json:"套接字接口路径"`
	DeadGWDetectEnabled          bool      `json:"备份网关"`
	DefaultIPGateway             []string  `json:"默认网关组"`
	DefaultTOS                   uint8     `json:"数据包标头设置值"`
	DefaultTTL                   uint8     `json:"TTL值"`
	DHCPEnabled                  bool      `json:"开启DHCP"`
	DHCPLeaseExpires             time.Time `json:"DHCP到期日期"`
	DHCPLeaseObtained            time.Time `json:"DHCP租约时间"`
	DHCPServer                   string    `json:"DHCPServer"`
	DNSDomain                    string    `json:"DNSDomain"`
	DNSDomainSuffixSearchOrder   []string
	DNSEnabledForWINSResolution  bool
	DNSHostName                  string
	DNSServerSearchOrder         []string
	DomainDNSRegistrationEnabled bool
	ForwardBufferMemory          uint32
	FullDNSRegistrationEnabled   bool
	GatewayCostMetric            []int64
	IGMPLevel                    uint8
	Index                        uint32
	InterfaceIndex               uint32
	IPAddress                    []string
	IPConnectionMetric           uint32
	IPEnabled                    bool
	IPFilterSecurityEnabled      bool
	IPPortSecurityEnabled        bool
	IPSecPermitIPProtocols       []string
	IPSecPermitTCPPorts          []string
	IPSecPermitUDPPorts          []string
	IPSubnet                     []string
	IPUseZeroBroadcast           bool
	IPXAddress                   string
	IPXEnabled                   bool
	IPXFrameType                 []uint32
	IPXMediaType                 uint32
	IPXNetworkNumber             []string
	IPXVirtualNetNumber          string
	KeepAliveInterval            uint32
	KeepAliveTime                uint32
	MACAddress                   string
	MTU                          uint32
	NumForwardPackets            uint32
	PMTUBHDetectEnabled          bool
	PMTUDiscoveryEnabled         bool
	ServiceName                  string `json:"服务名称"`
	SettingID                    string `json:"对象标识符"`
	TcpipNetbiosOptions          uint32 `json:"NetBIOS相关位图"`
	TcpMaxConnectRetransmissions uint32 `json:"重新传输超时"`
	TcpMaxDataRetransmissions    uint32 `json:"每次连续重新传输"`
	TcpNumConnections            uint32 `json:"最大连接数"`
	TcpUseRFC1122UrgentPointer   bool   `json:"RFC1122规范"`
	TcpWindowSize                uint16 `json:"最大TCP接收窗口大小"`
	WINSEnableLMHostsLookup      bool   `json:"是否开启WINS本地查找文件"`
	WINSHostLookupFile           string `json:"WINS文件的路径"`
	WINSPrimaryServer            string `json:"主WINS服务器IP地址"`
	WINSScopeID                  string `json:"域标识数据包"`
	WINSSecondaryServer          string `json:"WINS服务器IP地址"`
}

func NetInfo() (info []Win32_NetworkAdapter, err error) {
	err1 := wmi.Query("Select * from Win32_NetworkAdapter", &info)
	if err1 != nil {
		return nil, err1
	}

	return info, nil
}

func JsonNetInfo() (f []byte, err error) {
	cpu, err := NetInfo()
	if err != nil {
		return f, err
	}
	t, jsonerr := json.Marshal(cpu)
	if jsonerr != nil {
		return f, jsonerr
	}
	return t, nil

}
func MapNetInfo() (data []map[string]interface{}, err error) {

	bus, err := JsonNetInfo()
	if err != nil {
		return data, err
	}
	json.Unmarshal(bus, &data)
	cfg, err1 := ini.Load("./info/netconfig.ini")
	if err1 != nil {
		return data, err
	}
	//fmt.Println(cfg.Section(cfg.Section("").Key("理总线类型").String()).Key("1").String())
	list := []string{"网络适配器介质类型", "可用性", "错误代码", "物理媒体类型", "逻辑设备的状态", "连接到网络的状态"}
	for _, v := range data {
		for _, vl := range list {
			switch v[vl].(type) {
			case float64:
				v[vl] = cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(v[vl].(float64)))).String()
			case []interface{}:
				valstring := []string{}
				for _, v2 := range v[vl].([]interface{}) {
					vs := v2.(float64)
					valstring = append(valstring, cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(vs))).String())
				}
				v[vl] = valstring

			}
			if a, ok := v[vl].(float64); ok {
				v[vl] = cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(a))).String()
			} else {
				continue
			}

		}
	}
	return data, nil
}

func CIMNetInfo() (info []CIM_NetworkPort, err error) {
	err1 := wmi.Query("Select * from CIM_NetworkPort", &info)
	if err1 != nil {
		return nil, err1
	}

	return info, nil
}

func JsonCIMNetInfo() (f []byte, err error) {
	cpu, err := CIMNetInfo()
	if err != nil {
		return f, err
	}
	t, jsonerr := json.Marshal(cpu)
	if jsonerr != nil {
		return f, jsonerr
	}
	return t, nil

}
func MapCIMNetInfo() (data []map[string]interface{}, err error) {

	bus, err := JsonCIMNetInfo()
	if err != nil {
		return data, err
	}
	json.Unmarshal(bus, &data)
	cfg, err1 := ini.Load("./info/netconfig.ini")
	if err1 != nil {
		return data, err
	}
	//fmt.Println(cfg.Section(cfg.Section("").Key("理总线类型").String()).Key("1").String())
	list := []string{"网络适配器介质类型", "可用性", "错误代码", "物理媒体类型"}
	for _, v := range data {
		for _, vl := range list {
			switch v[vl].(type) {
			case float64:
				v[vl] = cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(v[vl].(float64)))).String()
			case []interface{}:
				valstring := []string{}
				for _, v2 := range v[vl].([]interface{}) {
					vs := v2.(float64)
					valstring = append(valstring, cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(vs))).String())
				}
				v[vl] = valstring

			}
			if a, ok := v[vl].(float64); ok {
				v[vl] = cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(a))).String()
			} else {
				continue
			}

		}
	}
	return data, nil
}
